package org.balthie.demo.opensource.apache.poi.SSXS;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SXSSFUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SXSSFUtils.class);
    
    public static SXSSFWorkbook readExcel(String path)
    {
        InputStream is = SXSSFUtils.class.getResourceAsStream(path);
        try
        {
            XSSFWorkbook wb = new XSSFWorkbook(is);
            SXSSFWorkbook swb = new SXSSFWorkbook(wb);
           
            return swb;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public static File writeLocaFile(Workbook wb, String filePath) throws IOException
    {
        String path = filePath;
        File file = null;
        
        try
        {
            file = new File(filePath);
            if(!file.exists())
            {
                try
                {
                    file.createNewFile();
                }
                catch (Exception e)
                {
                    LOGGER.warn("file.createNewFile failed use tempFile originalFileName {}", filePath, e);
                    file = File.createTempFile(path, "analyse");
                }
            }
            
            LOGGER.info("fileAbsolutePath:{}", file.getAbsolutePath());
            wb.write(new FileOutputStream(file));
            return file;
        }
        catch (IOException e)
        {
            LOGGER.error(" writeLocaFile fail" + e.getMessage());
            throw e;
        }
        finally
        {
        }
        
    }
}
